package com.nlp.solve.issue_d;

import com.alibaba.fastjson.JSONObject;
import com.nlp.model.Article;
import com.nlp.solve.Main;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class Issue_D {
    private static final Logger logger = LoggerFactory.getLogger(Issue_D.class);
    private static Set<String> set = new HashSet<>();

    static {
//        set.add("issue_b.json");
        set.add("issue_a_all.json");
        set.add("result.json");

    }

    private static Pattern pattern = Pattern.compile("\\((.*?)\\)");

    public static void main(String[] args) throws IOException {
        String dir = "F:\\IdeaProjects\\NLP2.0\\src\\test\\tmp\\";
        Issue_D issue_d = new Issue_D();
        issue_d.resolve(dir, "F:\\IdeaProjects\\NLP2.0\\src\\test\\tmp\\issue_d\\issue_d_.json");
//        issue_d.excel("F:\\IdeaProjects\\NLP2.0\\src\\test\\tmp\\issue_d\\issue_d.json");
//        Matcher matcher = pattern.matcher("name(liyuan)");
//        while (matcher.find()){
//            System.out.println(matcher.group());
//        }

    }


    public void resolve(String dir, String outputFile) throws IOException {
        Main main = new Main();
        File file = new File(dir);
        Map<String, Integer> map = new TreeMap<>();
        resolve(file, map);
        ArrayList<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
        main.quickSort(list, 0, list.size() - 1);
        Main.write(list, outputFile);
        logger.info("Finished resolving!");
    }

    private void excel(String abs) throws IOException {
        logger.info("开始导出到excel: {}", abs);
        List<Map.Entry> list = JSONObject.parseArray(Main.read(abs), Map.Entry.class);
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        int index = 0;
        HSSFRow row0 = sheet.createRow(index);
        row0.createCell(0).setCellValue("id");
        row0.createCell(1).setCellValue("机构");
        row0.createCell(2).setCellValue("发文量");
        row0.createCell(3).setCellValue("占比");
        row0.createCell(4).setCellValue("国家");
        int sum = 0;
        for (Map.Entry<String, Integer> entry : list) {
            Integer value = entry.getValue();
            sum += value;
        }

        for (Map.Entry<String, Integer> entry : list) {
            if (index > 1000) {
                break;
            }
            HSSFRow row = sheet.createRow(++index);
            row.createCell(0).setCellValue(index);
            row.createCell(1).setCellValue(entry.getKey());
            row.createCell(2).setCellValue(entry.getValue());
            row.createCell(3).setCellValue(BigDecimal.valueOf(entry.getValue() * 100.0 / (double) sum).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "%");
            Matcher matcher = pattern.matcher(entry.getKey());
            String country = "";
            if (matcher.find()) {
                country = matcher.group();
                if (country.length() > 2) {
                    country = country.substring(1, country.length() - 1);
                }
            }
            row.createCell(4).setCellValue(country);
        }
        try (DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("./issue_d.xlsx")))) {
            workbook.write(dataOutputStream);
        }
        logger.info("导出到excel: {}", abs);
    }

    private void resolve(File f, Map<String, Integer> map) throws IOException {
        //机构 （国家）： 发文量
        File[] files = f.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                resolve(file, map);
                continue;
            }
            resolve_(file, map);
        }
    }

    private static void resolve_(File file, Map<String, Integer> map) throws IOException {
        if (set.contains(file.getName()) || file.getName().contains("statistic") || file.getName().contains("issue")) {
            return;
        }
        logger.info("Resolving: {}", file.getAbsolutePath());
        List<Article> articles = JSONObject.parseArray(Main.read(file.getAbsolutePath()), Article.class);
        for (Article article : articles) {//此处需要改成学科
//            String[] fus = article.getFU();
            String[] infos = article.getC1();
            if (infos != null && infos.length != 0) {
                for (String fu : infos) {
                    //System.out.println(fu);
                    String[] split = fu.split("]");
                    String organization = split[split.length - 1];
                    map.put(organization, map.getOrDefault(organization, 0) + 1);
                }
            }
        }
    }
}
